//
//  PPAppDelegate.m
//  PetParadise
//
//  Created by Frank on 7/31/14.
//  Copyright (c) 2014 whalefin. All rights reserved.
//

#import "PPAppDelegate.h"
#import "supportingHeadFiles.h"
#import "PPSystemConfiguraton.h"
#import "SBJson.h"
#import "EaseMob.h"


#import "PPTopic.h"
#import "PPPetInfo.h"
#import "PPCirclePush.h"
#import "PPApplyNotification.h"

#import "UMSocial.h"
#import "UMSocialWechatHandler.h"
#import "UMSocialQQHandler.h"

#import "MobClick.h"
#import "PPCameraAuthorization.h"

#import "PPRequestTableTableViewController.h"

#define SUPPORT_IOS8 1

static const CGFloat kDefaultPlaySoundInterval = 3.0;

@implementation PPAppDelegate



-(void)setNavigationSytle
{
    if (IS_OS_7_OR_LATER ) {
        [[UINavigationBar appearance] setBarTintColor:[UIColor colorWithRed:171/255.0 green:206/255.0 blue:3/255.0 alpha:1.0]];
        [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
        [[UINavigationBar appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]}];
        [[UITabBar appearance] setSelectedImageTintColor:[UIColor colorWithRed:0/255.0 green:163/255.0 blue:244/255.0 alpha:1.0]];
    }else{
        [[UINavigationBar appearance] setTintColor:[UIColor colorWithRed:171/255.0 green:206/255.0 blue:3/255.0 alpha:1.0]];
        [[UINavigationBar appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]}];
        [[UITabBar appearance] setSelectedImageTintColor:[UIColor colorWithRed:0/255.0 green:163/255.0 blue:244/255.0 alpha:1.0]];
    }
}

-(void)alertShow :(NSString *)string
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:string delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
    [alert show];
}

- (void)autoLogin
{
    PPSystemConfiguraton *config = [PPSystemConfiguraton sharedSystemConfiguration];
    if ([config.userDefault boolForKey:@"autoLogin"]) {
        [HUD showUIBlockingIndicatorWithText:@"正在自动登录"];
        NSString *url = [PPAPIList getAPIList].PPLogin;
        NSMutableDictionary *params = [[NSMutableDictionary alloc] initWithDictionary:@{@"phoneNum":[config.userDefault objectForKey:@"userName"],@"loginPassword":[config.userDefault objectForKey:@"userPassWord"]}];
        if (config.pushId.length > 0 && config.pushId) {
            [params setObject:config.pushId forKey:@"pushKey"];
            [params setObject:@(4) forKey:@"deviceType"];
        }
        [httpRequst POST:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSNumber *processResultNumber = responseObject[@"processResult"];
            if (processResultNumber.integerValue == 1) {
                //宠缘服务器登录成功
                NSDictionary *resultMap = responseObject[@"resultMap"];
                NSDictionary *userDic = resultMap[@"user"];
                NSArray *friendList = resultMap[@"userList"];
                NSArray *applyList = resultMap[@"applyList"];
                NSError *err = nil;
                if (applyList) {
                    config.applyArray = [PPApplyNotification arrayOfModelsFromDictionaries:applyList error:&err];
                }
                
                if (friendList) {
                    //好友列表获得
                    config.friendArray = [PPUserInfo arrayOfModelsFromDictionaries:friendList error:&err];
                }
                //获取登录用户的信息
                config.userInfo = [[PPUserInfo alloc] initWithDictionary:userDic error:&err];
                [config getUserSettingwithCompletion:nil];
                //宠物 话题 会话 列表接受
                [config getConversationListwithComepletion:nil];
                [config getPetListwithComepletion:nil];
                [config getTopicListwithComepletion:nil];
                [config getCirclePushListwithCompletion:nil];
                
                //设置登录状态
                config.isLogin = YES;
                //环信登录
                [[EaseMob sharedInstance].chatManager asyncLoginWithUsername:[NSString stringWithFormat:@"%d",config.userInfo.id] password:[config.userDefault objectForKey:@"userPassWord"] completion:^(NSDictionary *loginInfo, EMError *error) {
                    if (loginInfo && !error) {
                        //环信服务器登陆成功
                        config.isEaseMobLogin = YES;
                        NSLog(@"环信登录成功");
                    }else {
                        config.isEaseMobLogin = NO;
                    }
                    [HUD hideUIBlockingIndicator];
                    //登录完成
                } onQueue:nil];
            }else{
                config.isLogin = NO;
                [self alertShow:responseObject[@"errorMsg"]];
                [HUD hideUIBlockingIndicator];
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error){
            config.isLogin = NO;
            config.isEaseMobLogin = NO;
            [self alertShow:@"网络不给力"];
            [HUD hideUIBlockingIndicator];
        }];
    }
}

-(void)getBreedPlist
{
    NSString *url = [PPAPIList getAPIList].PPQueryPetBreed;
    [httpRequst POST:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *resultMap = responseObject[@"resultMap"];
        NSArray *petList = resultMap[@"petList"];
        NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
        if (petList) {
            NSFileManager *fileManager = [NSFileManager defaultManager];
            //找到Documents文件所在的路径
            NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            //取得第一个Documents文件夹的路径
            NSString *filePath = [path objectAtIndex:0];
            //把TestPlist文件加入
            NSString *plistPath = [filePath stringByAppendingPathComponent:@"petBreed.plist"];
//            if ([fileManager fileExistsAtPath:plistPath]) {
//                return;
//            }
            NSDictionary *petTypeDic = petList.firstObject;
            NSArray *keyArray = [petTypeDic allKeys];
            for (NSString *key in keyArray) {
                NSArray *petTypeList = [petTypeDic objectForKey:key];
                //某类宠物的具体类型列表
                NSMutableArray *breedList = [NSMutableArray array];
                //宠物的大类
                NSString *type;
                for (NSDictionary *petDic in petTypeList) {
                    type = petDic[@"petType"];
                    NSString *breed = petDic[@"petBreed"];
                    [breedList addObject:breed];
                }
                [dic setObject:breedList forKey:type];// = @{type:breedList};
                
//                [typeDic setValue:breedList forKey:type];
//                [petTypeArray addObject:typeDic];
            }
            //开始创建文件
            [fileManager createFileAtPath:plistPath contents:nil attributes:nil];
            [dic writeToFile:plistPath atomically:YES];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}



- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
//    [[UIApplication sharedApplication] setStatusBarHidden:YES];
    // 要使用百度地图，请先启动BaiduMapManager
    _mapManager = [[BMKMapManager alloc]init];
    // 如果要关注网络及授权验证事件，请设定     generalDelegate参数
    BOOL ret = [_mapManager start:@"sdr1awqBnqh6ULitx0671fwH"  generalDelegate:nil];
    if (!ret) {
        NSLog(@"manager start failed!");
    }
    
    //百度推送初始化
    [BPush setupChannel:launchOptions];
    [BPush setDelegate:self];
#if SUPPORT_IOS8
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        UIUserNotificationType myTypes = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound;
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:myTypes categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    }else
#endif
    {
        UIRemoteNotificationType myTypes = UIRemoteNotificationTypeBadge|UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeSound;
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:myTypes];
    }
    
//    54115bd856240b8bff0017c8
    //友盟
    [UMSocialData setAppKey:@"54a44f54fd98c59ae100082f"];
    //weiChat
    [UMSocialWechatHandler setWXAppId:@"wx6806aeeb01c5fa45" appSecret:@"6fd8b47f5165f76378b407a045558a7e" url:@"https://itunes.apple.com/US/app/id887775175"];
    
    //QQ
    [UMSocialQQHandler setQQWithAppId:@"1103270439" appKey:@"Avq9Pw8u1ja049CP" url:@"https://itunes.apple.com/US/app/id887775175"];
    
    
    //检测更新
    [MobClick startWithAppkey:@"54a44f54fd98c59ae100082f" reportPolicy:BATCH  channelId:nil];
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    [MobClick setAppVersion:version];
//    [MobClick checkUpdate:@"有新版本更新" cancelButtonTitle:nil otherButtonTitles:@"现在就去"];
    [MobClick checkUpdateWithDelegate:self selector:@selector(appUpdate:)];
    
    //autoLogin
//    [self autoLogin];
    [self getBreedPlist];
    [self setNavigationSytle];
    [[PPSystemConfiguraton sharedSystemConfiguration] getOfficeTopic];
    [[PPSystemConfiguraton sharedSystemConfiguration] getKeyWord];
    [PPCameraAuthorization getCameraAuthorization];
    
    
    //easeMobSDK
    NSString *apnsCertName = @"petPushProduct";
    [[EaseMob sharedInstance] registerSDKWithAppKey:@"fundoing#sandbox" apnsCertName:apnsCertName];
#if DEBUG
    [[EaseMob sharedInstance] enableUncaughtExceptionHandler];
#endif
    //以下一行代码的方法里实现了自动登录，异步登录，需要监听[didLoginWithInfo: error:]
    //demo中此监听方法在MainViewController中
    [[EaseMob sharedInstance] application:application didFinishLaunchingWithOptions:launchOptions];
    //注册为SDK的ChatManager的delegate (及时监听到申请和通知)
    [[EaseMob sharedInstance].chatManager removeDelegate:self];
    [[EaseMob sharedInstance].chatManager addDelegate:self delegateQueue:nil];
    
    NSDictionary *remoteNotification = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    
    if (remoteNotification) {
        NSLog(@"push %@",remoteNotification);
    }
    return YES;
}


- (void)appUpdate:(NSDictionary *)appInfo
{
    NSString *isUpdate = appInfo[@"update"];
    if (isUpdate.boolValue) {
        [UIAlertView showWithTitle:@"有新版本可用" message:nil cancelButtonTitle:nil otherButtonTitles:@[@"马上更新"] tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
            if (buttonIndex == 0) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://itunes.apple.com/US/app/id887775175"]];
            }
        }];
    }
//    nss
    
}


-(BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    return  [UMSocialSnsService handleOpenURL:url];
}

- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation
{
    return  [UMSocialSnsService handleOpenURL:url];
}

- (void) onMethod:(NSString*)method response:(NSDictionary*)data {
    NSLog(@"On method:%@", method);
    NSLog(@"data:%@", [data description]);
    NSDictionary* res = [[NSDictionary alloc] initWithDictionary:data];
    if ([BPushRequestMethod_Bind isEqualToString:method]) {
        NSString *appid = [res valueForKey:BPushRequestAppIdKey];
        NSString *userid = [res valueForKey:BPushRequestUserIdKey];
        NSString *channelid = [res valueForKey:BPushRequestChannelIdKey];
        //NSString *requestid = [res valueForKey:BPushRequestRequestIdKey];
        int returnCode = [[res valueForKey:BPushRequestErrorCodeKey] intValue];
        if (returnCode == BPushErrorCode_Success) {
            // 在内存中备份，以便短时间内进入可以看到这些值，而不需要重新bind
            self.appId = appid;
            self.channelId = channelid;
            self.userId = userid;
            [PPSystemConfiguraton sharedSystemConfiguration].pushId = userid;
            [self autoLogin];
        }
    } else if ([BPushRequestMethod_Unbind isEqualToString:method]) {
        int returnCode = [[res valueForKey:BPushRequestErrorCodeKey] intValue];
        if (returnCode == BPushErrorCode_Success) {
            
        }
    }
}
//注册通知设置
#if SUPPORT_IOS8
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
    //register to receive notifications
    [application registerForRemoteNotifications];
}
#endif


- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    //环信
    [[EaseMob sharedInstance] application:application didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];

    //百度推送
    [BPush registerDeviceToken: deviceToken];
    [BPush bindChannel];
}

//注册推送失败
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"%@",error);
    if(error){
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"注册推送失败"
                                                        message:@""
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
        [self autoLogin];
    }
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    NSLog(@"%@", userInfo);
    UIApplicationState state = [application applicationState];
    // user tapped notification while app was in background
    if (state == UIApplicationStateInactive || state == UIApplicationStateBackground) {
        PPSystemConfiguraton *config = [PPSystemConfiguraton sharedSystemConfiguration];
        int code = [userInfo[@"pushCode"] intValue];
        if (code == 200) {
            //接受到好友申请
            [config getApplyListwithComepletion:^{
                UITabBarController *rootVC =(UITabBarController *) self.window.rootViewController;
                [rootVC setSelectedIndex:1];
            }];
        }else if (code == 300){
            //接受到好友申请的处理结果
            [config getFriendListwithComepletion:^{
                [config getConversationListwithComepletion:^{
                    UITabBarController *rootVC =(UITabBarController *) self.window.rootViewController;
                    [rootVC setSelectedIndex:1];
                }];
            }];
        }else if (code == 400){
            //被邀请加入群组
            
        }else if (code == 500){
            //宠友圈新回复
            [config getCirclePushListwithCompletion:^{
                UITabBarController *rootVC =(UITabBarController *) self.window.rootViewController;
                [rootVC setSelectedIndex:2];
            }];
        }else if (code == 600){
            //新消息 聊天
            [config getConversationListwithComepletion:^{
                UITabBarController *rootVC =(UITabBarController *) self.window.rootViewController;
                [rootVC setSelectedIndex:1];
            }];
        }else{
            //环信
            [[EaseMob sharedInstance] application:application didReceiveRemoteNotification:userInfo];
        }
    } else {
        //do nothing
        NSLog(@"do nothing");
    }
//    [BPush handleNotification:userInfo]; // 可选
}

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
    [[EaseMob sharedInstance] application:application didReceiveLocalNotification:notification];
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    [[EaseMob sharedInstance] applicationWillResignActive:application];
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"applicationDidEnterBackground" object:nil];
    [[EaseMob sharedInstance] applicationDidEnterBackground:application];
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    [[EaseMob sharedInstance] applicationWillEnterForeground:application];
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    
    [[EaseMob sharedInstance] applicationDidBecomeActive:application];
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    [[EaseMob sharedInstance] applicationWillTerminate:application];
}

#pragma mark - IChatManagerDelegate 收到新的聊天信息
-(void)didReceiveMessage:(EMMessage *)message{
    [self playSoundAndVibration];
}

- (void)playSoundAndVibration{
    PPSystemConfiguraton *config = [PPSystemConfiguraton sharedSystemConfiguration];
    //如果距离上次响铃和震动时间太短, 则跳过响铃
    NSLog(@"%@, %@", [NSDate date], self.lastPlaySoundDate);
    NSTimeInterval timeInterval = [[NSDate date]
                                   timeIntervalSinceDate:self.lastPlaySoundDate];
    if (timeInterval < kDefaultPlaySoundInterval) {
        return;
    }
    //保存最后一次响铃时间
    self.lastPlaySoundDate = [NSDate date];
    
    
    if (config.userSetting.voice == 1) {
        // 收到消息时，播放音频
        [[EaseMob sharedInstance].deviceManager asyncPlayNewMessageSound];
    }
    if (config.userSetting.shock == 1) {
        // 收到消息时，震动
        [[EaseMob sharedInstance].deviceManager asyncPlayVibration];
    }
    
}


#pragma mark - IChatManagerDelegate 登录状态变化
- (void)didLoginFromOtherDevice
{
    PPSystemConfiguraton *config = [PPSystemConfiguraton sharedSystemConfiguration];
    NSString *url = [PPAPIList getAPIList].PPLogout;
    NSDictionary *params = @{@"userId":@(config.userInfo.id)};
    [httpRequst POST:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject){
        config.isLogin = NO;
        //提示
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示"
                                                            message:@"你的账号已在其他地方登录"
                                                           delegate:self
                                                  cancelButtonTitle:@"确定"
                                                  otherButtonTitles:nil,
                                  nil];
        [alertView show];
        if (config.isEaseMobLogin) {
            [[EaseMob sharedInstance].chatManager asyncLogoffWithCompletion:^(NSDictionary *info, EMError *error) {
                
                config.isEaseMobLogin = NO;
                [self goLogin];
            } onQueue:nil];
        }else{
            [self goLogin];
        }
    }failure:^(AFHTTPRequestOperation *operation, NSError *error){
        
    }];
}

- (void)goLogin
{
    UIStoryboard *secondStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    UIViewController *theInitialViewController = [secondStoryboard instantiateViewControllerWithIdentifier:@"loginViewController"];
    [self.window.rootViewController presentViewController:theInitialViewController animated:YES completion:nil];
}

#pragma mark - IChatManagerDelegate 好友变化


#pragma mark - IChatManagerDelegate 群组变化
/*!
 @method
 @brief 收到加入群组的申请
 @param groupId         要加入的群组ID
 @param groupname   要加入的群名
 @param username   申请人的用户名
 @param reason          申请理由
 */
- (void)didReceiveApplyToJoinGroup:(NSString *)groupId
                         groupname:(NSString *)groupname
                     applyUsername:(NSString *)username
                            reason:(NSString *)reason
                             error:(EMError *)error
{
//    if (!groupId || !username) {
//        return;
//    }
//    
//    if (!reason || reason.length == 0) {
//        reason = [NSString stringWithFormat:@"申请加入群组\'%@\'", groupname];
//    }
//    else{
//        reason = [NSString stringWithFormat:@"申请加入群组\'%@\'：%@", groupname, reason];
//    }
//    
//    if (error) {
//        NSString *message = [NSString stringWithFormat:@"发送申请失败:%@\n原因：%@", reason, error.description];
//        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"错误" message:message delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//        [alertView show];
//    }
//    else{
//        NSString *url = [PPAPIList getAPIList].PPQueryUserMsgByUserId;
//        NSDictionary *params =@{@"userId":username};
//        [httpRequst POST:url parameters:params success:^(AFHTTPRequestOperation *operation,id responseObject){
//            NSNumber *processResult = responseObject[@"processResult"];
//            if (processResult.intValue == 1) {
//                NSDictionary *resultMap = responseObject[@"resultMap"];
//                NSDictionary *userDic = resultMap[@"user"];
//                NSError *err = nil;
//                PPUserInfo *user = [[PPUserInfo alloc] initWithDictionary:userDic error:&err];
//                NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:@{@"title":groupname, @"groupId":groupId, @"username":username, @"groupname":groupname, @"applyMessage":[NSString stringWithFormat:@"%@ %@",user.userName, reason], @"applyStyle":[NSNumber numberWithInteger:ApplyStyleJoinGroup]}];
////                [[PPSystemConfiguraton sharedSystemConfiguration] addNewApply:dic];
//            }
//        }failure:^(AFHTTPRequestOperation *operation, NSError *error){
//            NSLog(@"%@",error);
//        }];
//    }
}

/*!
 @method
 @brief 收到了其它群组的加入邀请
 @param groupId  群组ID
 @param username 邀请人名称
 @param message  邀请信息
 @discussion
 */

- (void)didReceiveGroupInvitationFrom:(NSString *)groupId
                              inviter:(NSString *)username
                              message:(NSString *)message
{
//    if (!groupId || !username) {
//        return;
//    }
//    
//    NSString *groupName = groupId;
//    if (!message || message.length == 0) {
//        message = [NSString stringWithFormat:@"邀请你加入群组\'%@\'", groupName];
//    }
//    
//    
//    NSString *url = [PPAPIList getAPIList].PPQueryUserMsgByUserId;
//    NSDictionary *params =@{@"userId":username};
//    [httpRequst POST:url parameters:params success:^(AFHTTPRequestOperation *operation,id responseObject){
//        NSLog(@"%@",responseObject);
//        NSNumber *processResult = responseObject[@"processResult"];
//        if (processResult.intValue == 1) {
//            NSDictionary *resultMap = responseObject[@"resultMap"];
//            NSDictionary *userDic = resultMap[@"user"];
//            NSError *err = nil;
//            PPUserInfo *user = [[PPUserInfo alloc] initWithDictionary:userDic error:&err];
//            NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:@{@"title":groupName, @"groupId":groupId, @"username":username, @"applyMessage":[NSString stringWithFormat:@"%@ %@",user.userName ,message], @"applyStyle":[NSNumber numberWithInteger:ApplyStyleGroupInvitation]}];
////            [[PPSystemConfiguraton sharedSystemConfiguration] addNewApply:dic];
//        }
//    }failure:^(AFHTTPRequestOperation *operation, NSError *error){
//        NSLog(@"%@",error);
//    }];
}

/*!
 @method
 @brief 邀请别人加入群组, 但被别人拒绝后的回调
 @param groupId  群组ID
 @param username 拒绝的人的用户名
 @param reason   拒绝理由
 */
- (void)didReceiveGroupRejectFrom:(NSString *)groupId
                          invitee:(NSString *)username
                           reason:(NSString *)reason
{
    
}

//加群后同意
- (void)didReceiveAcceptApplyToJoinGroup:(NSString *)groupId
                               groupname:(NSString *)groupname
{
    
}

//加群后拒绝
- (void)didReceiveRejectApplyToJoinGroupFrom:(NSString *)fromId
                                   groupname:(NSString *)groupname
                                      reason:(NSString *)reason
{
    if (!reason || reason.length == 0) {
        reason = [NSString stringWithFormat:@"被拒绝加入群组\'%@\'", groupname];
    }
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"申请提示" message:reason delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alertView show];
}

//被踢出群组
- (void)group:(EMGroup *)group didLeave:(EMGroupLeaveReason)reason error:(EMError *)error
{
    NSString *tmpStr = group.groupSubject;
    NSString *str;
    if (!tmpStr || tmpStr.length == 0) {
        NSArray *groupArray = [[EaseMob sharedInstance].chatManager groupList];
        for (EMGroup *obj in groupArray) {
            if ([obj.groupId isEqualToString:group.groupId]) {
                tmpStr = obj.groupSubject;
                break;
            }
        }
    }
    
    if (reason == eGroupLeaveReason_BeRemoved) {
        str = [NSString stringWithFormat:@"你被从群组\'%@\'中踢出", tmpStr];
    }
    if (str.length > 0) {
//        TTAlertNoTitle(str);
    }
}



#pragma mark - push

- (void)didBindDeviceWithError:(EMError *)error
{
    if (error) {
        NSLog(@"消息推送与设备绑定失败");
    }
}


@end
